package ktvutil

import (
	"encoding/binary"
	"io"
	//"syscall"
	"unicode/utf16"
)

// ErrorString implements Error's String method by returning itself.
type ErrorString string

func (e ErrorString) Error() string { return string(e) }

// NewError converts s to an ErrorString, which satisfies the Error interface.
func NewError(s string) error { return ErrorString(s) }

var (
	EINVAL = NewError("bad arg in system call")
)

// 写入UTF16的字符串
// 先把utf8的字符串转换成
func WriterUtf16String(w io.Writer, strUtf8 string) {
	binary.Write(w, binary.LittleEndian, StringToUtf16(strUtf8))
}

// utf8转utf16
func StringToUtf16(s string) []uint16 {
	return StringToUTF16(s)
}

// utf16转utf8
func Utf16ToUtf8(s []uint16) string {
	return UTF16ToString(s)
}

//
func Utf16ByteToUtf8(s []byte) string {

	vp := []uint16{}
	nLength := len(s)

	for i := 0; i < nLength; i += 2 {
		ch := uint16(s[i]) | uint16(s[i+1])<<8
		vp = append(vp, ch)
	}

	return UTF16ToString(vp)
}

//////////////////////////////////

// StringToUTF16 returns the UTF-16 encoding of the UTF-8 string s,
// with a terminating NUL added. If s contains a NUL byte this
// function panics instead of returning an error.
//
// Deprecated: Use UTF16FromString instead.
func StringToUTF16(s string) []uint16 {
	a, err := UTF16FromString(s)
	if err != nil {
		panic("syscall: string with NUL passed to StringToUTF16")
	}
	return a
}

// UTF16FromString returns the UTF-16 encoding of the UTF-8 string
// s, with a terminating NUL added. If s contains a NUL byte at any
// location, it returns (nil, EINVAL).
func UTF16FromString(s string) ([]uint16, error) {
	for i := 0; i < len(s); i++ {
		if s[i] == 0 {
			return nil, EINVAL
		}
	}
	return utf16.Encode([]rune(s + "\x00")), nil
}

// UTF16ToString returns the UTF-8 encoding of the UTF-16 sequence s,
// with a terminating NUL removed.
func UTF16ToString(s []uint16) string {
	for i, v := range s {
		if v == 0 {
			s = s[0:i]
			break
		}
	}
	return string(utf16.Decode(s))
}

// StringToUTF16Ptr returns pointer to the UTF-16 encoding of
// the UTF-8 string s, with a terminating NUL added. If s
// If s contains a NUL byte this function panics instead of
// returning an error.
//
// Deprecated: Use UTF16PtrFromString instead.
func StringToUTF16Ptr(s string) *uint16 { return &StringToUTF16(s)[0] }

// UTF16PtrFromString returns pointer to the UTF-16 encoding of
// the UTF-8 string s, with a terminating NUL added. If s
// contains a NUL byte at any location, it returns (nil, EINVAL).
func UTF16PtrFromString(s string) (*uint16, error) {
	a, err := UTF16FromString(s)
	if err != nil {
		return nil, err
	}
	return &a[0], nil
}
